﻿using Microsoft.IdentityModel.Tokens;
using supermarket.info;
using supermarket.method;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static Azure.Core.HttpHeader;

namespace supermarket
{
    public partial class supgiftmanage : Form
    {
        public SqlConnection sql = new Classgetsql().getcon();
        string imagePath = "";//图片的路径
        public supgiftmanage ()
        {
            InitializeComponent();
        }

        private void supgiftmanage_Load ( object sender, EventArgs e )
        {
            LoadData(dv, "gift");
            dv.DoubleClick += dv_CellDoubleClick;
        }

        #region 加载信息

        public void LoadData ( DataGridView dgv, string tableType )
        {
            try
            {
                string query;
                Classgetsql sqlcon = new Classgetsql();
                SqlConnection con = sqlcon.getcon();
                SqlDataAdapter adapter;
                DataTable dataTable = new DataTable();

                switch (tableType.ToLower())
                {
                    case "gift":
                        query = @"SELECT TOP (1000) [id],[giftname],[number],[integral],[imgsrc] FROM [super].[dbo].[Table_gift]";
                        adapter = new SqlDataAdapter(query, con);
                        adapter.Fill(dataTable);

                        // 确保 imgsrc 列是 DataGridViewImageColumn 类型
                        if (!dgv.Columns.Contains("imgsrc") || !(dgv.Columns["imgsrc"] is DataGridViewImageColumn))
                        {
                            if (dgv.Columns.Contains("imgsrc"))
                            {
                                dgv.Columns.Remove("imgsrc");
                            }
                            DataGridViewImageColumn imageColumn = new DataGridViewImageColumn
                            {
                                Name = "imgsrc",
                                HeaderText = "图片",
                                DataPropertyName = "imgsrc",
                                ImageLayout = DataGridViewImageCellLayout.Zoom
                            };
                            dgv.Columns.Add(imageColumn);
                        }

                        dgv.DataSource = dataTable;

                        // 设置列标题
                        dgv.Columns["id"].HeaderText = "ID";
                        dgv.Columns["giftname"].HeaderText = "礼品名称";
                        dgv.Columns["number"].HeaderText = "数量";
                        dgv.Columns["integral"].HeaderText = "所需积分";
                        dgv.Columns["imgsrc"].HeaderText = "图片";

                        // 遍历每一行，将二进制数据转换为图片
                        foreach (DataGridViewRow row in dgv.Rows)
                        {
                            if (row.Cells["imgsrc"].Value != null && row.Cells["imgsrc"].Value != DBNull.Value)
                            {
                                try
                                {
                                    byte[] imageData = (byte[])row.Cells["imgsrc"].Value;
                                    using (MemoryStream ms = new MemoryStream(imageData))
                                    {
                                        row.Cells["imgsrc"].Value = Image.FromStream(ms); // 从二进制数据加载图片
                                    }
                                }
                                catch (Exception ex)
                                {
                                    row.Cells["imgsrc"].Value = null; // 加载失败显示空
                                                                      // 可记录日志：Console.WriteLine($"加载图片失败: {ex.Message}");
                                }
                            }
                            else
                            {
                                row.Cells["imgsrc"].Value = null; // 没有图片数据
                            }
                        }
                        break;
                    default:
                        throw new ArgumentException("无效的参数");
                }
                con.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载数据时发生错误: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        private void button16_Click ( object sender, EventArgs e )
        {
            if (string.IsNullOrEmpty(txtname.Text) || string.IsNullOrEmpty(txtnumber.Text))
            {
                MessageBox.Show("ID、礼品名称和数量不能为空！");
                return;
            }

            if (string.IsNullOrEmpty(imagePath))
            {
                MessageBox.Show("请选择礼品图片！");
                return;
            }

            SaveGiftWithImageBinary(1, txtname.Text, int.Parse(txtnumber.Text), int.Parse(txtintegral.Text), imagePath);
            LoadData(dv, "gift");
            ClearGiftInputFields();
        }

        private void button15_Click ( object sender, EventArgs e )
        {
            if (string.IsNullOrEmpty(txtid.Text))
            {
                MessageBox.Show("请先选择要修改的礼品！");
                return;
            }

            if (string.IsNullOrEmpty(txtname.Text) || string.IsNullOrEmpty(txtnumber.Text))
            {
                MessageBox.Show("礼品名称和数量不能为空！");
                return;
            }

            UpdateGiftWithImageBinary(int.Parse(txtid.Text), txtname.Text, int.Parse(txtnumber.Text), int.Parse(txtintegral.Text), imagePath);
            LoadData(dv, "gift");
            ClearGiftInputFields();
        }

        private void button18_Click ( object sender, EventArgs e )
        {
            if (string.IsNullOrEmpty(txtid.Text))
            {
                MessageBox.Show("请先选择要删除的礼品！");
                return;
            }

            DeleteGift(int.Parse(txtid.Text));
        }

        private void button19_Click ( object sender, EventArgs e )
        {
            ClearGiftInputFields();
        }

        private void button13_Click ( object sender, EventArgs e )
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Image Files|*.jpg;*.jpeg;*.png";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                imagePath = openFileDialog.FileName;
                pictureBox1.Image = System.Drawing.Image.FromFile(imagePath);
            }
        }

        private void button12_Click ( object sender, EventArgs e )
        {
            pictureBox1.Image = null;
            imagePath = "";
        }

        private void dv_CellDoubleClick ( object sender, EventArgs e )
        {
            DataGridViewRow row = dv.CurrentRow;
            if (row != null)
            {
                txtid.Text = row.Cells["id"].Value.ToString();
                txtname.Text = row.Cells["giftname"].Value.ToString();
                txtnumber.Text = row.Cells["number"].Value.ToString();
                txtintegral.Text = row.Cells["integral"].Value.ToString();

                // 处理图片显示
                if (row.Cells["imgsrc"].Value != null && row.Cells["imgsrc"].Value != DBNull.Value)
                {
                    try
                    {
                        byte[] imageData = (byte[])row.Cells["imgsrc"].Value;
                        using (MemoryStream ms = new MemoryStream(imageData))
                        {
                            pictureBox1.Image = Image.FromStream(ms);
                            // 保存当前图片路径为空，表示使用原有图片
                            imagePath = "";
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"加载图片时发生错误：{ex.Message}");
                        pictureBox1.Image = null;
                        imagePath = "";
                    }
                }
                else
                {
                    pictureBox1.Image = null;
                    imagePath = "";
                }
            }
        }

        public void SaveGiftWithImageBinary ( int id, string giftName, int number, int integral, string imagePath )
        {
            try
            {
                byte[] imageData = File.ReadAllBytes(imagePath);
                string query = "INSERT INTO Table_gift ( giftname, number, integral, imgsrc) VALUES ( @giftname, @number, @integral, @imgsrc)";
                using (SqlCommand cmd = new SqlCommand(query, sql))
                {
                    cmd.Parameters.AddWithValue("@giftname", giftName);
                    cmd.Parameters.AddWithValue("@number", number);
                    cmd.Parameters.AddWithValue("@integral", integral);
                    cmd.Parameters.Add("@imgsrc", System.Data.SqlDbType.VarBinary, -1).Value = imageData;
                    cmd.ExecuteNonQuery();
                }
                MessageBox.Show("礼品和图片保存成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败: {ex.Message}");
            }
        }

        public void UpdateGiftWithImageBinary ( int id, string giftName, int number, int integral, string imagePath )
        {
            try
            {
                string query;
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = sql;

                if (!string.IsNullOrEmpty(imagePath))
                {
                    // 如果有新图片，更新所有字段包括图片
                    byte[] imageData = File.ReadAllBytes(imagePath);
                    query = @"UPDATE Table_gift 
                            SET giftname = @giftname, 
                                number = @number, 
                                integral = @integral, 
                                imgsrc = @imgsrc 
                            WHERE id = @id";
                    cmd.CommandText = query;
                    cmd.Parameters.AddWithValue("@id", id);
                    cmd.Parameters.AddWithValue("@giftname", giftName);
                    cmd.Parameters.AddWithValue("@number", number);
                    cmd.Parameters.AddWithValue("@integral", integral);
                    cmd.Parameters.Add("@imgsrc", System.Data.SqlDbType.VarBinary, -1).Value = imageData;
                }
                else
                {
                    // 如果没有新图片，只更新其他字段
                    query = @"UPDATE Table_gift 
                            SET giftname = @giftname, 
                                number = @number, 
                                integral = @integral 
                            WHERE id = @id";
                    cmd.CommandText = query;
                    cmd.Parameters.AddWithValue("@id", id);
                    cmd.Parameters.AddWithValue("@giftname", giftName);
                    cmd.Parameters.AddWithValue("@number", number);
                    cmd.Parameters.AddWithValue("@integral", integral);
                }

                int rowsAffected = cmd.ExecuteNonQuery();
                if (rowsAffected > 0)
                {
                    MessageBox.Show("礼品信息更新成功！");
                }
                else
                {
                    MessageBox.Show("没有找到要更新的礼品记录！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"更新失败: {ex.Message}");
            }
        }

        private void DeleteGift ( int id )
        {
            try
            {
                DialogResult result = MessageBox.Show("确定要删除该礼品吗？", "确认删除",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    string deleteQuery = "DELETE FROM Table_gift WHERE id = @Id";
                    using (SqlCommand deleteCommand = new SqlCommand(deleteQuery, sql))
                    {
                        deleteCommand.Parameters.AddWithValue("@Id", id);
                        int rowsAffected = deleteCommand.ExecuteNonQuery();
                        MessageBox.Show(rowsAffected > 0 ? "礼品删除成功！" : "礼品删除失败。");
                        LoadData(dv, "gift");
                        ClearGiftInputFields();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除礼品时发生错误：{ex.Message}");
            }
        }

        private void ClearGiftInputFields ()
        {
            txtid.Text = "";
            txtname.Text = "";
            txtnumber.Text = "";
            txtintegral.Text = "";
            pictureBox1.Image = null;
            imagePath = "";
        }

    }
}
